# -*- coding:utf-8 -*-
import socket
import ConfigParser
from dm_py_util import ERROR_LOG, INFO_LOG, DEBUG_LOG


class TCPClient(object):
    _sock = None
    _closed = None

    def __init__(self, path='', client_name='', *args, **kw):
        self._path = path
        self._name = client_name
        self.args = args
        self.kw = kw

    def init(self, config):
        config_parser = ConfigParser.ConfigParser()
        config_parser.read(config)
        host = config_parser.get('TCPClient', 'host')
        port = eval(config_parser.get('TCPClient', 'port'))
        self._path = (host, port)

    def path(self):
        return self._path

    def name(self):
        return self._name

    def sock(self):
        return self._sock

    def build(self):
        try:
            if isinstance(self._path, tuple):
                client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                INFO_LOG('create AF_INER socket')
            else:
                client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                INFO_LOG('create AF_UNIX socket')
            client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #关闭后地址立即重用
            client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)  #keepalive
            #client.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 32 * 1024)  #发送缓存区大小
            #client.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32 * 1024)  #收送缓存区大小
            client.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 30)    #x秒无数据往来开始探测
            client.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 5)    #探测发包时间间隔
            client.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 5)      #探测次数
            client.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)      #no delay
            client.settimeout(1)
            self.on_build()
            client.connect(self._path)
            client.setblocking(0)
            INFO_LOG(" client build by ", self.path, client.fileno())
            self._sock = client
            self._closed = False
            self.on_connect()
        except socket.error as e:
            ERROR_LOG("Connect server failed: ", e, "path:", self._path)
            self._sock = None
            self._closed = True
            self.on_error(str(e))

    def on_build(self):
        pass

    def on_error(self, reason):
        pass

    def on_connect(self):
        pass


    def fileno(self):
        return self._sock.fileno()

    def close(self):
        try:
            print 'try to close sock'
            self._sock.close()
        except Exception as e:
            ERROR_LOG('close tcp client error', e)
        self._closed = True

    def send(self, data):
        self._sock.send(data)

    def recv(self):
        return self._sock.recv()

    def closed(self):
        return self._closed


if __name__ == '__main__':
    path = ('', 9203)
    tcp_client = TCPClient(path)
    #tcp_client.init('./tcp_client.config')
    tcp_client.build()
    print tcp_client.path()
    tcp_client.send('hahah')
    print tcp_client.closed()
    print tcp_client.sock()
    print tcp_client.fileno()
    tcp_client._sock.close()
    tcp_client._sock.close()
    tcp_client.close()
    print tcp_client.closed()
    print tcp_client.sock()

